<template>
  <van-form @submit="onSubmit" class="login">
    <div class="title">登录</div>
  <van-cell-group inset>
    <van-field
      v-model="username"
      name="userAccount"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="password"
      type="password"
      name="userPassword"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
  </van-cell-group>
  <div class="err">用户名密码错误</div>
  <div class="sign" @click="tosign">没有账号？点我注册</div>
  <div style="margin: 20px;">
    <van-button round block type="primary" native-type="submit">
      登录
    </van-button>
  </div>
</van-form>
</template>

<script>
import { Form, Field, CellGroup,Button } from 'vant';
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import axios from 'axios'
export default {
    components:{
        'van-form':Form,
        'van-field':Field,
        'van-button':Button,
        'van-cell-group':CellGroup
    },
    mounted(){
      // console.log(this.$refs.form.submit) 
    },
    methods:{
      tosign(){
          this.$router.push({path:'/sign'})
      }
    },
    setup() {
      const router = useRouter()
      const store = useStore()
      const username = ref('');
      const password = ref('');
      const onSubmit = (values) => {
        // 登录请求
        axios.post('http://10.136.9.228:10010/auth/login?userAccount='+values.userAccount+'&userPassword='+values.userPassword)
        .then(res => {
          return res.data
        }).then(res=>{
          console.log('进入登录方法');
          // 登录成功,提示成功信息，然后跳转到首页，同时将token保存到localstorage中, 将登录名使用vuex传递到Home页面
          if(res.msg === "success"){
            console.log(res)
            // 跳转到首页
            setTimeout(function(){
                router.push({path:'/'})
            },1000)
            localStorage.setItem('token',res.jwt)
            // 将登录名使用vuex传递到Home页面
            store.commit('setUserInfo',res.userInfo.userUsername,res.userInfo.userId,res.userInfo.userHeadimageurl);
          }else{
            console.log('登录失败')
          }
        }).catch(function(err){
          console.log("服务器错误");
        })
      };
      return {
        setUserName: () => store.commit('setUserInfo',res.userInfo.userUsername,res.userInfo.userId,res.userInfo.userHeadimageurl),
        username,
        password,
        onSubmit
      };
    }
}
</script>

<style scoped>
.login{
    min-width: 100%; 
    padding-top: 10em;
    min-height: 100%; 
    position: absolute;
    background-color: rgb(247, 248, 250);
}
.sign{
    margin: 1em auto 2em 2em;
    color: blue;
}
.title{
  font-size: 2em;
  padding-bottom: 1em;
  text-align: center;
}
.err{
  color: red;
  padding-top: 1em;
  padding-bottom: 1em;
  text-align: center;
}
</style>